import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:grocery_app_demo/api/entity/goods_list_res_entity.dart';
import 'package:grocery_app_demo/api/scm_api.dart';
import 'package:grocery_app_demo/widgets/gap.dart';

class SelectGoodsLogic extends GetxController {
  RxList<GoodsListResEntity> goodsList = RxList();

  RxSet<String> selected = RxSet();
  RxBool finishLoad = RxBool(false);

  TextEditingController searchCtrl = TextEditingController();
  RxString searchWord = RxString("");

  void Function(List<GoodsListResEntity> goodsInfo)? callback;

  bool isSelected(String goodsCode) {
    return selected.contains(goodsCode);
  }

  List<GoodsListResEntity> getSelectGoodsList() {
    return goodsList
        .where((element) => selected.contains(element.goodsCode))
        .toList();
  }

  @override
  void onReady() {
    ScmApi().getList<GoodsListResEntity>(ScmApi.listGoods).then((value) {
      goodsList.value = value;
      finishLoad.value = true;
    });

    callback = Get.arguments['callback'];
    selected.addAll(Get.arguments['selected']);
  }

  List<GoodsListResEntity> getFilteredGoodsLit() {
    if (searchWord.trim().isEmpty) {
      return goodsList;
    } else {
      RegExp exp = RegExp(searchWord.trim(), caseSensitive: false);
      return goodsList.where((g) => exp.hasMatch(g.goodsName)).toList();
    }
  }

  List<Widget> buildList() {
    var list = <Widget>[];

    var goodsList = getFilteredGoodsLit();
    for (int i = 0; i < goodsList.length; i++) {
      var g = goodsList[i];
      list.add(InkWell(
        child: ListTile(
          selected: isSelected(g.goodsCode),
          title: Text(g.goodsName),
          selectedColor: Colors.green,
          trailing: isSelected(g.goodsCode)
              ? const Icon(Icons.check_box)
              : const Icon(Icons.check_box_outline_blank),
        ),
        onTap: () {
          if (selected.contains(g.goodsCode)) {
            selected.remove(g.goodsCode);
          } else {
            selected.add(g.goodsCode);
          }
        },
      ));
      list.add(line);
    }

    return list;
  }
}
